import SqLite from "./index";

const dbTable = "logData";

/**
 * id  唯一
 * cmd 蓝牙指令
 * sub 子命令
 * data 有效数据帧
 */
const column = ["id", "fileName", "level", "action", "log", "date", "ts"];
const tableData = "'id' INTEGER PRIMARY KEY AUTOINCREMENT, fileName TEXT, level TEXT, action TEXT, log TEXT, date TEXT, ts INTEGER";

const openSqLite = async () => {
	if (SqLite.isOpen()) {
		return await SqLite.createTable(dbTable, tableData);
	} else {
		try {
			await SqLite.openSqlite();
		} catch (error) {
			console.log("openSqLite error", error);
			
		}
		return await SqLite.createTable(dbTable, tableData);
	}
};

const closeSqlite = () => {
	return SqLite.closeSqlite();
};

const insertData = async (fileName, level, action, log, date, ts) => {
	return SqLite.insertTableData(
		dbTable,
		`'${fileName}', '${level}', '${action}', '${log}', '${date}',${ts}`,
		"fileName, level, action, log, date, ts"
	);
};

/**
 *  删除传入时间7天前的数据
 * @param {*} ts
 * @returns
 */
const deleteDataBefore7 = (ts) => {
	if (!isValidTimestamp(ts)) throw new TypeError("Invalid timestamp");
	return SqLite.deleteTableDataByCustomConditions(dbTable, `ts < ${ts}`);
};

function isValidTimestamp(ts) {
	// 检查类型
	if (typeof ts !== "number") {
		return false;
	}

	// 检查范围（假设我们只考虑 1970 年到 2038 年的有效时间戳）
	const minTimestamp = 0; // 1970-01-01 00:00:00 UTC
	const maxTimestamp = 2147483647; // 2038-01-19 03:14:07 UTC (32-bit signed integer)

	if (ts < minTimestamp || ts > maxTimestamp) {
		return false;
	}

	// 检查转换为日期是否有效
	const date = new Date(ts * 1000); // 如果是秒级时间戳，乘以 1000 转换为毫秒
	return date instanceof Date && !isNaN(date);
}

// const selectData = ({ cmd, sub, ts, symbol = "=", sort = "DESC", order = "ts" }) => {
// 	let con = "";
// 	if (cmd) {
// 		con += `cmd = '${cmd}' `;
// 		if (sub) {
// 			con += `AND sub = '${sub}' `;
// 		}
// 	}
// 	if (ts && symbol) {
// 		if (symbol !== "=" || symbol !== ">=" || symbol !== "<=" || symbol !== "<" || symbol !== ">") {
// 			symbol = "=";
// 		}
// 		con += `AND ts ${symbol} ${ts} `;
// 	}
// 	if (column.includes(order)) {
// 		con += `ORDER BY ${order} `;
// 	}

// 	if (sort === "DESC" || sort === "ASC") {
// 		con += `${sort} `;
// 	}

// 	return SqLite.selectTableDataByCustomConditions(dbTable, con);
// };

export default { openSqLite, closeSqlite, insertData, deleteDataBefore7 };
